<script setup lang="ts">
  import { computed, ref } from 'vue'
  import { useSearchStore } from '@/stores/modules/search'
  import { addSearchHistory, searchHistory, serach } from '@/services/search'
  import { onLoad } from '@dcloudio/uni-app'
  import type { historyDataType, InfoListItem } from '@/types/search'
  const searchStore = useSearchStore()
  // 获取屏幕边界到安全区域距离
  const { safeAreaInsets } = uni.getSystemInfoSync()

  // 搜索start

  /* 搜索的接口需要的参数 */
  const params = ref({
    page: 1,
    size: 10,
    content: '',
  })
  // 搜索关键词
  // const searchKeyword = ref('')
  // 搜索结果
  const searchResults = ref([])
  // 是否正在搜索
  const isSearching = ref(false)
  // 搜索框是否获得焦点
  const isSearchFocused = ref(false)

  // 获取历史搜索记录
  /* const historyList = computed(() => searchStore.historyList) */
  // 从接口获取搜索历史记录
  const historyList = ref<historyDataType[]>([])
  const getSearchHistory = async () => {
    const res = await searchHistory()
    /* 搜索历史记录进行去重 */
    historyList.value = res.data
    // console.log(res)
  }
  getSearchHistory()

  /* 新增历史记录 */
  const addSearchHistoryData = async () => {
    const res = await addSearchHistory(params.value.content)
    // console.log(res)
  }

  // 搜索框获得焦点
  const handleFocus = () => {
    isSearchFocused.value = true
  }

  // 搜索框失去焦点
  const handleBlur = () => {
    isSearchFocused.value = false
    isSearching.value = false
    // 清空搜索结果
    searchResults.value = []
  }
  /* 发送网络请求 */
  /* 查询结果展示 */
  const SearchResult = ref<InfoListItem[]>([])
  const searchdata = async () => {
    const res = await serach(params.value)
    SearchResult.value = res.data.info_list
    // const historyRes = await searchHistory()
    const exists = historyList.value.some((item) => item.content === params.value.content)
    console.log(res)
    console.log(exists)

    if (exists) {
      const result = await addSearchHistory({
        content: params.value.content,
      })
    } else {
      // 1. 先移除已有记录
      historyList.value = historyList.value.filter((item) => item.content !== params.value.content)
      // 2. 再重新添加（会自动排到最前）
      await addSearchHistory({ content: params.value.content })
    }
    getSearchHistory()
    isSearching.value = true
  }

  // 搜索方法
  const handleSearch = async () => {
    if (!params.value.content.trim()) {
      uni.showToast({ title: '请输入搜索关键词', icon: 'none' })
      return
    }

    try {
      // 先执行搜索（主要功能）
      await searchdata()

      // 搜索成功后再记录历史
      // await addSearchHistoryData()

      // 最后刷新历史记录
      await getSearchHistory()

      isSearching.value = true
    } catch (err) {
      console.log(err)
    }
  }

  // 点击历史记录项进行搜索
  const searchHistoryItem = (history : string) => {
    params.value.content = history
    handleSearch()
  }
  // 搜索end
</script>

<template>
  <view class="navbar">
    <!-- logo文字 -->
    <view class="logo">
      <image class="logo-image" src="@/static/images/logo_row.png"></image>
      <text class="logo-text">新鲜 · 亲民 · 快捷</text>
    </view>

    <!-- 搜索条 -->
    <view class="search">
      <view class="input">
        <text class="iconfont icon-sousuo" @click="handleSearch"></text>
        <input type="text" class="search-input" placeholder="搜索商品" v-model="params.content" @confirm="handleSearch"
          @focus="handleFocus" @blur="handleBlur" />
        <text class="icon-scan"></text>
      </view>
    </view>

    <!-- 历史搜索记录  -->
    <view class="history-container" v-if="!isSearching">
      <view class="history-title">搜索历史</view>
      <view class="history-containerp-content">
        <view class="history-item" v-for="(history, index) in historyList" :key="index"
          @click="searchHistoryItem(history.content)">
          {{ history.content }}
        </view>
      </view>
    </view>

    <!-- 模拟搜索结果展示，后面应该有接口了是直接展示到搜索结果页面? -->
    <view class="search-results" v-else>
      <navigator v-for="item in SearchResult" :key="item.id" :url="`/pages/goods/goods?id=${item.id}`"
        class="product-card" :class="{ 'sold-out': item.spec[0]?.stock === '0' }">
        <view class="img-box">
          <img :src="item.pictureList[0]?.url || ''" :alt="item.name" class="product-image" />
        </view>

        <view class="product-info">
          <view class="product-details">
            <h3 class="product-title">{{ item.name }}</h3>
            <view class="product-description">
              <text>{{ item.mealdesc }}</text>
            </view>
          </view>
          <view class="product-price">
            <view class="price-info">
              <span class="current-price">¥{{ item.spec[0]?.price || 2.0 }}</span>
            </view>
          </view>
        </view>
      </navigator>
    </view>
  </view>
</template>

<style lang="scss">
  /* 自定义导航条 */
  .navbar {
    background-image: url(@/static/images/navigator_bg.png);
    background-size: cover;
    position: relative;
    display: flex;
    flex-direction: column;
    padding-top: 20px;

    .logo {
      display: flex;
      align-items: center;
      height: 64rpx;
      padding-left: 30rpx;

      .logo-image {
        width: 166rpx;
        height: 60rpx;
      }

      .logo-text {
        flex: 1;
        line-height: 28rpx;
        color: #fff;
        margin: 2rpx 0 0 20rpx;
        padding-left: 20rpx;
        border-left: 1rpx solid #fff;
        font-size: 26rpx;
      }
    }

    .search {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 64rpx;
      margin: 16rpx 20rpx;
      padding: 0 10rpx;
      color: #fff;
      font-size: 28rpx;
      border-radius: 32rpx;
      background-color: rgba(255, 255, 255, 0.5);

      .input {
        flex: 1;
        height: 100%;

        font-size: 28rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .search-input {
          flex: 1;
          color: #fff;
        }

        .search-input::placeholder {
          color: #fff;
        }

        .icon-search {
          font-size: 30rpx;
          padding: 15rpx;
        }

        .icon-scan {
          font-size: 30rpx;
          padding: 15rpx;
        }
      }
    }

    /* 历史搜索 */
    .history-container {
      width: 100vw;
      height: 400rpx;

      background-color: #fff;
      box-sizing: border-box;
      padding: 20rpx;

      // color: #ccc;
      .history-title {
        padding: 20rpx;
        font-size: 34rpx;
        font-weight: bold;
        color: #333;
      }

      .history-containerp-content {
        width: 100%;
        display: flex;
        flex-wrap: wrap;

        .history-item {
          padding: 10rpx 20rpx;
          margin: 10rpx 20rpx;
          background-color: #f5f5f5;
          // border-radius: 10rpx;
        }
      }
    }

    /* 搜索结果 */
    .search-results {
      width: 100%;
      height: 300rpx;
      position: absolute;
      top: 228rpx;
      left: 0;

      background-color: #fff;
      z-index: 999;
      box-sizing: border-box;
      padding: 0 20rpx;

      .result-item {
        padding: 20rpx 0;
        border-bottom: 1rpx solid #f5f5f5;
        font-size: 28rpx;
        color: #333;
      }
    }

    .icon-search {
      &::before {
        margin-right: 10rpx;
      }
    }

    .icon-scan {
      font-size: 30rpx;
      padding: 15rpx;
    }
  }

  .product-card {
    display: flex;
    // 用来设置商品遮罩
    position: relative;
    background-color: #fff;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin: 0 0 20rpx 0;
    width: 100%;
    height: 200rpx;
    // background-color: #27ba9b;
    padding: 20rpx;
    box-sizing: border-box;

    navigator {
      background-color: #fff;
    }

    .img-box {
      width: 160rpx;
      height: 160rpx;
      // background-color: #f0f0f0;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 20rpx;
      overflow: hidden;

      .product-image {
        width: 100%;
        height: 100%;
      }
    }

    .product-info {
      flex: 1;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      // background-color: #cf4444;

      .product-details {
        width: 100%;
        flex: 1;
      }

      .product-title {
        font-size: 16px;
        font-weight: 600;
        // margin-bottom: 5rpx;
        color: #333;

        width: 100%;
        // background-color: #fff;
        white-space: nowrap; // 禁止换行
        overflow: hidden; // 超出部分隐藏
        text-overflow: ellipsis; // 超出部分显示省略号
      }
    }

    .product-description {
      font-size: 14px;
      color: #666;
      width: 450rpx;

      text {
        display: inline-block;
        // margin-bottom: 4px;
        width: 100%;
        // background-color: mediumvioletred;
        white-space: nowrap; // 禁止换行
        overflow: hidden; // 超出部分隐藏
        text-overflow: ellipsis; // 超出部分显示省略号

        font-size: 12px;
      }
    }

    .product-price {
      display: flex;
      justify-content: space-between;
      align-items: center;
      // background-color: blueviolet;
      width: 100%;
      height: 60rpx;
      // margin-top: auto;
      // padding-top: 10px;
      // border-top: 1px solid #eee;

      .price-info {

        // margin-right: 5rpx;
        .current-price {
          font-size: 16px;
          color: red;
        }

        .original-price {
          font-size: 14px;
          color: #999;
          text-decoration: line-through;
          margin-left: 5px;
        }
      }

      .quantity-control {
        display: flex;
        align-items: center;
        width: 100%;
        width: 140rpx;

        // background-color: darkred;
        .quantity-btn {
          width: 32px;
          height: 26px;
          border: none;
          border-radius: 4px;
          background-color: #4caf50;
          color: white;
          font-size: 16px;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          // margin-left: 8px;

          &.minus {
            background-color: #8bc34a;
          }
        }

        .quantity {
          // margin: 0 auto;
          font-size: 14px;
          color: #333;
          min-width: 24px;
          text-align: center;
        }
      }
    }
  }

  .sold-out {
    .product-info {
      .product-title {
        color: #a6a6a6;
      }
    }

    .product-description {
      color: #bebebe;
    }

    .product-price {


      .price-info {

        // margin-right: 5rpx;
        .current-price {
          color: #bebebe;
        }

        .soldoutText {

          color: #c0c0c0;
        }

        .original-price {
          color: #999;
        }
      }


    }
  }

  .product-card.sold-out::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #e0e0e0;
    /* 白色背景 */
    background-color: rgba(255, 255, 255, 0.7);
    z-index: 99;
    opacity: 0.7;
  }
</style>
